//go:build !windows && !nacl && !plan9
// +build !windows,!nacl,!plan9

package logx

import (
	"io"
	"log/syslog"

	"github.com/sirupsen/logrus"
)

// SyslogHook is a hook that writes logs of specified LogLevels to specified Writer
type SyslogHook struct {
	Writer        io.Writer
	LogLevels     []logrus.Level
	SyslogNetwork string
	SyslogRaddr   string
}

func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {
	w, err := syslog.Dial(network, raddr, priority, tag)
	return &SyslogHook{
		Writer:        w,
		SyslogNetwork: network,
		SyslogRaddr:   raddr,
	}, err
}

// Fire will be called when some logging function is called with current hook
// It will format log entry to string and write it to appropriate writer
func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
	line, err := entry.String()
	if err != nil {
		return err
	}
	_, err = hook.Writer.Write([]byte(line))
	return err
}

// Levels define on which log levels this hook would trigger
func (hook *SyslogHook) Levels() []logrus.Level {
	return hook.LogLevels
}

// setupLogs adds hooks to send logs to different destinations depending on level
func setupLogs(logger *logrus.Logger, hook *SyslogHook) *logrus.Logger {
	// logrus.SetOutput(io.Discard) // Send all logs to nowhere by default

	hook.LogLevels = []logrus.Level{
		logrus.PanicLevel,
		logrus.FatalLevel,
		logrus.ErrorLevel,
		logrus.WarnLevel,
	}
	logger.AddHook(hook)

	hook.LogLevels = []logrus.Level{
		logrus.InfoLevel,
		logrus.DebugLevel,
	}
	logger.AddHook(hook)

	return logger
}
